import React from "react";
import {observer, inject} from 'mobx-react';
import {toJS} from 'mobx';
import {withRouter} from 'react-router-dom';
import {Checkbox, Tools, Toast, Icon} from "weaver-mobile";
import {ListAdvanced, RouteLayout} from 'weaver-mobile-page';

import '../style/index.less'
import * as commonUtil from "../../../util/CommonUtil"
import SignInput from "../../signlog/public/SignInput";
import * as SIUtil from "../../../util/SignInputUtil";
import * as mobx from "mobx";

const ButtonGroup = RouteLayout.ButtonGroup;
const AgreeItem = Checkbox.AgreeItem;

const getLabel = Tools.getLabel;

@withRouter
@inject("odocComsStore", "managerWithDrawStore")
@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    componentWillUnmount() {
        const {managerWithDrawStore} = this.props;
        managerWithDrawStore.destory();
    }

    componentDidMount() {
        this.loadData();
        window.onresize = () => {
            this.updateHeight();
        }
    }

    componentWillMount() {
        const {managerWithDrawStore, location, odocComsStore} = this.props;
        const {init} = managerWithDrawStore;
        let {requestParam = {}} = odocComsStore;
        requestParam = mobx.toJS(requestParam);
        delete requestParam.markInfo;

        const prepath = location.pathname;

        init(prepath, requestParam);
    }

    /**
     * 加载数据
     */
    loadData() {
        const {managerWithDrawStore} = this.props;
        const {getData} = managerWithDrawStore;
        getData();
    }

    render() {
        const {managerWithDrawStore} = this.props;
        const {listAd, dataParams, isinit} = managerWithDrawStore;
        const {params, contionUrl} = dataParams;

        if (!isinit) {
            return <div></div>
        }

        return (
            <div>
                <ListAdvanced
                    className={"withDrawList"}
                    store={listAd}
                    rowKey={"id"}
                    treeKey="id"
                    hasAdvanceSerach={true}
                    showSearchBar={true}
                    selectedProps={getLabel('30690', "条数据")}
                    conditionFetchOptions={{//高级搜索
                        url: contionUrl,
                        method: "POST",
                        params: {...params},
                    }}
                    showCheck={true}
                    searchBarProps={{
                        showSelectButton: false,
                        extraButton: [
                            {key: 'advanceds', show: getLabel(511633, "请选择要撤回的在办人员")},
                            // { key: 'advanced',className:"showtest", show: this.showSelectAdvanced()},
                            { key: 'advancedsearch',className:"showtest", show:
                                    <span
                                        key="filter-o"
                                        style={{color: '#708090'}}
                                        type="filter-o"
                                        onClick={()=>{this.openLink()}}>
                                        <Icon type={"filter-o"}/></span>},
                        ]
                    }}
                    leftTreeBrowserProps={{
                        searchBarProps: {
                            placeholder: 'Search',
                        },
                    }}
                    onSearch={this.onSearch}
                    getTemplate={(template) => {
                        return ({json: this.getTemplate()})
                    }}
                />
                {this.getSignInputContent()}
                <ButtonGroup
                    data={this.getButtons()}
                    flexStyles={this.getFlextStyles()}
                />
            </div>
        );
    }

    updateHeight = () => {
        let listHeight = document.body.clientHeight || document.documentElement.clientHeight;
        listHeight = listHeight - 41;
        if (listHeight != this.state.listHeight) {
            this.setState({listHeight});
        }
    }

    /**
     * 签字意见组件
     * @returns {null}
     */
    getSignInputContent = () => {
        const {managerWithDrawStore, odocComsStore} = this.props;
        let {isShowSignInput = false, hiddenSignInput, submitparams, appendPickerRemark, changeSubmitParams} = managerWithDrawStore;
        const {remark = ""} = submitparams;
        const {workflowStores = {}} = odocComsStore;
        let signparams = {
            workflowStores: workflowStores,
            remark: remark,
            changeRemark: changeSubmitParams,
            appendRemark: appendPickerRemark,
        };

        return isShowSignInput ?
            <div className={"maskSign updateSign"}>
                <div>
                    <div className="wf-signView-panel-mask"
                         onClick={() => {
                             hiddenSignInput()
                         }}
                    ></div>
                    <div className="wf-signView-panel-content">
                        <SignInput {...signparams}/>
                    </div>
                </div>
            </div> : null;
    }


    getTemplate = () => {
        const template = [
            {
                key: 'col1',
                configs: [
                    {
                        key: 'row1',
                        render: (data, value, index) => {
                            const {
                                userdeptspan, userdept, userid, useridspan, nodeidspan, nodeid,
                                logtypespan, logtype, operatedatespan, operatedate, senderuserid,
                                senderuseridspan, isremarkspan, isremark
                            } = data;
                            return <div className={"list_row1_item"}>
                                <div className={"operator list_item"}>
                                    <span className={"title"}>{getLabel(16975, "发送人") + ":"}</span>
                                    <span className={"content"}>{senderuseridspan || senderuserid}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(519984, "流转环节") + ":"}</span>
                                    <span className={"content"}>{nodeidspan || nodeid}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(31389, "处理状态") + ":"}</span>
                                    <span className={"content"}>{isremarkspan || isremark}</span>
                                </div>
                                <div className={"operator list_item"}>
                                    <span className={"title"}>{getLabel(99, "操作者") + ":"}</span>
                                    <span className={"content"}>{useridspan || userid}</span>
                                </div>
                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(385898, "操作者部门") + ":"}</span>
                                    <span className={"content"}>{userdeptspan}</span>
                                </div>

                                <div className={"list_item"}>
                                    <span className={"title"}>{getLabel(21663, "操作日期") + ":"}</span>
                                    <span className={"content"}>{operatedatespan || operatedate}</span>
                                </div>
                            </div>
                        }
                    },
                ],
            },
        ]

        return template;
    }

    /**
     * 显示选中情况
     * @returns {*}
     */
    showSelectAdvanced = () => {
        const {managerWithDrawStore} = this.props;
        let prefixCls = "wm-list-advanced-body";
        const {listAd} = managerWithDrawStore;
        const {listViewStore} = listAd;
        const {isSelectedAll, selectedRowKeys, haveCheck} = listViewStore;
        return <span className={"select_advanced_body"}>
              <span>
                <span>{`${getLabel(500274, '已选择')}${selectedRowKeys ? selectedRowKeys.length : 0}${getLabel(30690, "条数据")}`}</span>
              </span>
            <span>
                <span
                    className={`${prefixCls}-all-select`}
                    onClick={() => (haveCheck && (isSelectedAll ? listViewStore.selectNone() : listViewStore.selectAll()))}
                >{`${isSelectedAll ? getLabel(31129, '取消') : ''}${getLabel(556, '全选')}`}</span>
              </span>
        </span>
    }

    /**
     * 点击高级搜索
     */
    openLink = () => {
        const {managerWithDrawStore} = this.props;
        const {listAd} = managerWithDrawStore;
        const {selectedListPageStore = {}} = listAd;
        const {route} = selectedListPageStore;
        this.props.history.push(`${route}/SearchAdvanced`);
    }

    /**
     * 搜索
     */
    onSearch = () => {
        const {managerWithDrawStore} = this.props;
        const {listAd, dataParams, type} = managerWithDrawStore;
        let {dataUrl, params = {}} = dataParams;
        const {searchAdvancedStore, listViewStore, searchParams} = listAd;
        // 搜索框等搜索数据
        let sparams = {...searchParams};
        // 获取高级搜索参数
        if (searchAdvancedStore) {
            const {formParams} = searchAdvancedStore.form;
            sparams = {...formParams};
        }
        listViewStore.selectNone();
        params = {...sparams, ...params, type}
        // 清除列表数据
        listViewStore.clearData();
        // 带参数请求列表数据
        listAd.getData({url: dataUrl, method: "POST", params});
    }

    /**
     * 取消
     */
    onCancel = () => {
        window && window.historyRoute && window.historyRoute.go && (window.historyRoute.go(-1));
    }

    /**
     * 提交
     */
    onSubmit = () => {
        const {managerWithDrawStore, odocComsStore} = this.props;
        const {submitCallBack: subCallback} = odocComsStore;
        let callback = (res) => {
            const {api_status, api_msg} = res;
            Toast.success(<span dangerouslySetInnerHTML={{__html: api_msg || getLabel(384408, "撤回成功")}}/>, 2);
            this.onCancel();
            typeof subCallback == "function" && subCallback(res);
        }

        const {listAd, doSave} = managerWithDrawStore;
        const {listViewStore} = listAd;
        const {selectedRowKeys, data = {}} = listViewStore;
        //这里可能会弹框
        let shownames = [], sld = [];

        selectedRowKeys && selectedRowKeys.length > 0 && data && data.map(item => {
            if (selectedRowKeys.indexOf(item.id) != -1) {
                shownames.push(item.useridspan);
                sld.push(item.id + "_" + item.isremark)
            }
        });
        if (shownames && shownames.length > 0) {
            //校验签字意见必填
            const {submitparams = {}, showSignInput} = managerWithDrawStore;

            if (!SIUtil.checkRemark(submitparams)) {
                showSignInput();
                Toast.info(getLabel(500238, "请输入签字意见！"), 1);
                return;
            }

            let shownamecontent;
            const cssText = "margin:0 5px; font-weight: bold;color: #2db7f5";

            if (shownames.length > 20) {
                shownamecontent = `<span style='${cssText}' title='${shownames.join(",")}'>${shownames.splice(0, 20).join(",") + "..."}</span>`;
            } else {
                shownamecontent = `<span style='${cssText}' title='${shownames.join(",")}'>${shownames.splice(0).join(",")}</span>`;

            }
            let showcon = getLabel(518350, "确认撤回#usernames#吗？");
            shownamecontent = showcon.replace("#usernames#", shownamecontent);
            let confirmMsg = <span dangerouslySetInnerHTML={{__html: shownamecontent}}/>;
            commonUtil.showConfirm({
                content: confirmMsg,
                okEvent: () => {
                    doSave(toJS(sld), callback);
                },
                cancelEvent: () => {
                }
            })
        } else {
            commonUtil.showConfirm({
                content: getLabel(511633, "请选择要撤回的在办人员") + "!",
                okEvent: () => {
                },
            })
        }
    }

    /**
     * 底部按钮
     * @returns {Array}
     */
    getButtons = () => {
        const {managerWithDrawStore} = this.props;
        const {isShowSignInput = false, showSignInput} = managerWithDrawStore;
        let buttons = [];
        !isShowSignInput && buttons.push({
            key: 'bianji',
            text: <Icon type={"bianji"}/>,
            onClick: showSignInput,
        });
        buttons.push({
            key: 'submit',
            text: getLabel(32025, "撤回"),
            onClick: this.onSubmit,
            type: 'primary',
        });
        return buttons;
    }

    /**
     * 显示按钮样式
     * @returns {{style: {flex: number}}[]}
     */
    getFlextStyles = () => {
        const {managerWithDrawStore} = this.props;
        const {coreparams = {}} = managerWithDrawStore;
        const flextStyles = [{
            style: {flex: 1}
        }, {
            style: {flex: 3}
        }
        ];
        return flextStyles;
    }
}